package com.heima.behavior.service.impl;

import com.heima.behavior.model.dto.ReadBehaviorDto;
import com.heima.behavior.model.entity.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.behavior.util.AppUserThreadLocalUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        //1. 校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 查询是否存在阅读行为
        Criteria criteria = new Criteria()
                .orOperator(Criteria.where("userId").is(AppUserThreadLocalUtil.get().getId()), Criteria.where("equipmentId").is(dto.getEquipmentId()))
                .andOperator(Criteria.where("articleId").is(dto.getArticleId()));

        Query query = Query.query(criteria);
        ApReadBehavior readBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);

        //2.1 如果存在, 数据累加
        if (readBehavior != null) {
            readBehavior.setCount(readBehavior.getCount() + 1);
            readBehavior.setReadDuration(readBehavior.getReadDuration() + dto.getReadDuration());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setUpdatedTime(new Date());

            mongoTemplate.save(readBehavior);
        } else {
            //2.2 如果不存在 , 新增数据
            readBehavior = new ApReadBehavior();
            readBehavior.setId(ObjectId.get().toHexString());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setCount(1);
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setEquipmentId(dto.getEquipmentId());
            readBehavior.setUserId(AppUserThreadLocalUtil.get() == null ? null : AppUserThreadLocalUtil.get().getId());
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setLoadDuration(dto.getLoadDuration());

            mongoTemplate.save(readBehavior);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
